// components/articleList/articleList.js
const app = getApp();
import LoginStore from '../../pages/login/store.js';
import { reqHeader } from '../../utils/util.js';
let getDefaultData = function () {
  return {
    listData: [],
    hasNext: true
  }
}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    urlStr: {
      type: String,
      value: '',
      observer: function (newVal, oldVal, changedPath) {

      }
    },
    params: {
      type: Object,
      value: {},
      observer: function (newVal, oldVal, changedPath) {
        if (newVal.page == 1) {
          this.setData(getDefaultData())
        }
        if (newVal.page && this.data.hasNext) {
          this._loadData(newVal);
        }
      }
    },
    totalPageUrl: {
      type: String,
      value: null
    },
    type: {
      type: String,
      value: 'large'
    }
  },

  /**
   * 组件的初始数据
   */
  data: getDefaultData(),

  /**
   * 组件的方法列表
   */
  methods: {
    resolveMsg: function (desc) {
      let msgTextList = [];
      let tplMsgStr = '';
      let res = desc.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\b(?:topic_id|user_id)="[^"]+">[\s\S]*?<\/a>/gi);
      if (res != null) {
        let resList = desc.split(/(<a\b[^>]+\bhref="[^"]*"[^>]*\b(?:topic_id|user_id)="[^"]+">[\s\S]*?<\/a>)/);
        resList.forEach((value, i) => {
          if (value) {
            let hasUser = value.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="[^"]+">[\s\S]*?<\/a>/gi);
            let hasTopic = value.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\btopic_id="[^"]+">[\s\S]*?<\/a>/gi);
            if (hasUser != null) {
              let splitRes = value.split(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="([^"]+)">([\s\S]*?)<\/a>/);
              let descStr = splitRes[2];
              if (!msgTextList.length) {
                descStr = descStr.replace(/(^\s*)/g, "");
              };
              msgTextList.push({
                type: 'user',
                desc: descStr,
                id: splitRes[1]
              })
            } else if (hasTopic != null) {
              let splitRes = value.split(/<a\b[^>]+\bhref="[^"]*"[^>]*\btopic_id="([^"]+)">([\s\S]*?)<\/a>/);
              let descStr = splitRes[2];
              if (!msgTextList.length) {
                descStr = descStr.replace(/(^\s*)/g, "");
              };
              msgTextList.push({
                type: 'topic',
                desc: descStr,
                id: splitRes[1]
              })
            } else {
              msgTextList.push({
                type: 'text',
                desc: value
              });
              tplMsgStr += value;
            }
          }
        })

      } else {
        msgTextList.push({
          type: 'text',
          desc: desc
        });
        tplMsgStr += desc;
      }

      return {
        msgTextList,
        tplMsgStr
      }
    },
    turnToLinkDetail(e) {
      let desc = e.currentTarget.dataset.desc;
      if (desc.type === 'topic') {
        wx.navigateTo({
          url: `/pages/topic/topic?topicId=${desc.id}`,
        })
      } else if (desc.type === 'user') {
        wx.navigateTo({
          url: `/pages/userInfo/userInfo?userId=${desc.id}`,
        })
      }
      return
    },
    _loadData: function (params) {
      let me = this;
      let userAccountInfo = LoginStore.userInfo || {};
      params['access_token'] = userAccountInfo.access_token;
      wx.request({
        url: this.properties.urlStr,
        data: params,
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200) {
            let hasNext = true;
            if (!res.data.length || res.data.length < (params.size || 20)) {
              hasNext = false;
            }
            res.data.forEach((item) => {
              item.resolvedDescription = {};
              if (item.description) {
                item.resolvedDescription = me.resolveMsg(item.description);
                item.topicList = [];
                item.userList = [];
                item.resolvedDescription.msgTextList.forEach((desc) => {
                  if (desc.type === 'topic') {
                    item.topicList.push(desc);
                  } else if (desc.type === 'user') {
                    item.userList.push(desc);
                  }
                })
              }
            })
            let listData = me.data.listData.concat(res.data);
            me.setData({
              listData: listData,
              hasNext: hasNext
            })
          } else {
            console.log(res.message);
          }
        }
      });
    },
    toArticleDetail: function (e) {
      let item = e.currentTarget.dataset.item;
      if (item.state == 1) {
        return;
      }

      let urlStr = `/pages/graphicDetail/graphicDetail?id=${item.id}&resourceType=${item.resourceType}`;
      let pageList = getCurrentPages();
      if (pageList.length >= 8) {
        wx.redirectTo({
          url: urlStr,
        })
      } else {
        wx.navigateTo({
          url: urlStr
        });
      }
    }
  }
})
